/**
*	信呼相关服务
*	开发者：雨中磐石(rainrock)
*	网址：http://www.rockoa.com/
*	时间：2019-07-17
*/

function rockBase(debug){
	var me = this;
	var debug_time=0;
	
	this.Minutes = 0;
	this.debug=function(str){
		if(debug){
			debug_time++;
			console.log(''+debug_time+'.['+this.getTimes()+']:'+str);
		}
	}
	
	this.now=function(type,sj){
		if(!type)type='Y-m-d';
		if(type=='now')type='Y-m-d H:i:s';
		var dt,ymd,his,weekArr,Y,m,d,w,H=0,i=0,s=0,W;
		if(typeof(sj)=='string')sj=sj.replace(/\//gi,'-');
		if(/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/.test(sj)){
			sj=sj.split(' ');
			ymd=sj[0];
			his=sj[1];if(!his)his='00:00:00';
			ymd=ymd.split('-');
			his=his.split(':');
			H = his[0];if(his.length>1)i = his[1];if(his.length>2)s = his[2];
			dt=new Date(ymd[0],ymd[1]-1,ymd[2],H,i,s);
		}else{
			dt=(typeof(sj)=='number')?new Date(sj):new Date();
		}
		weekArr=new Array('日','一','二','三','四','五','六');
		Y=dt.getFullYear();
		m=this.xy10(dt.getMonth()+1);
		d=this.xy10(dt.getDate());
		w=dt.getDay();
		H=this.xy10(dt.getHours());
		i=this.xy10(dt.getMinutes());
		s=this.xy10(dt.getSeconds());
		W=weekArr[w];
		if(type=='time'){
			return dt.getTime();
		}else{
			return type.replace('Y',Y).replace('m',m).replace('d',d).replace('H',H).replace('i',i).replace('s',s).replace('w',w).replace('W',W);
		}
	}
	this.xy10=function(s){
		var s1=''+s+'';if(s1.length<2)s1='0'+s+'';
		return s1;
	};
	
	//得出毫秒
	this.getTime=function(){
		var dt = new Date(),H,i,s;
		H = dt.getHours();
		i = dt.getMinutes();
		s = dt.getSeconds();
		this.Minutes = i;
		return parseInt(dt.getTime()*0.001);
	}
	
	//获取时间
	this.getTimes=function(){
		return this.now('H:i:s');
	}
	
	/**
	*	运行cmd
	*/
	this.execcmd=function(cmdStr){
		try{
			if(!this.processobj)this.processobj = require('child_process');
			me.debug('runcmd:'+cmdStr+'');
			this.processobj.exec(cmdStr, function(err,stdout,stderr){
				if(err) {
					me.debug('error:'+stderr);
				} else {
					me.debug(stdout);
					if(cmdStr.indexOf('addlog=true')>0)me.writeAppend('runcmd',''+cmdStr+'\n'+stdout+'');
				}
			});
		}catch(e){}
	}
	
	//http访问URL
	this.httpgetClass=function(url, fun, cnas){
		var mehttp	= this;
		this.url 	= url.toString();
		if(!this.url)return;
		if(!fun)fun = function(){};
		this.fun 	= fun;
		this.params	= cnas;
		this.httpget=function(){
			var qzs		= this.url.substr(0,5);
			var http 	= (qzs=='https') ? require('https') :  require('http');
			me.debug('runurl:'+this.url+'');
			http.get(this.url, (res) => {
				res.setEncoding('utf8');
				var statusCode 	= res.statusCode, headers = res.headers;
				var rawData 	= '';
				res.on('data', (chunk) => {
					rawData += chunk;
				});
				res.on('end', () => {
					me.debug(rawData);
					mehttp.fun(rawData, cnas);
					if(this.url.indexOf('addlog=true')>0)me.writeAppend('runurl',''+this.url+'\n'+rawData+'');
				});
				
			}).on('error', (e) => {
				me.debug('errhttp.get'+me.url+'');
			});
		}
		this.httpget();
	}
	
	var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	
	this.base64encode = function (input) {
		if(input=='' || input==null)return '';
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4,s;
		var i = 0;
		input = this._utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
			_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
			_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		s = output;
		s = s.replace(/\+/g, '!');	
		s = s.replace(/\//g, '.');	
		s = s.replace(/\=/g, ':');
		return s;
	}
	
	this._utf8_encode = function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
		return utftext;
	}
	
	this.writeLog=function(lx,time, cont){
		return;
		if(!this.fs)this.fs = require('fs');
		this.fs.writeFile(''+lx+'_'+time+'.log', cont,function(err){});
	};
	this.getFsobj=function(){
		if(!this.fs)this.fs = require('fs');
		return this.fs;
	}
	this.runurl=function(url, fun, cnas){
		try{
			new this.httpgetClass(url, fun, cnas);
		}catch(e){}
	}
	
	this.writeAppend=function(lx, cont){
		try{
			var path = ''+__dirname+'/'+lx+'_'+this.now('Ymd')+'.log';
			this.getFsobj().appendFile(path, ""+this.now('now')+":"+cont+"\n", 'utf8', function(){});
		}catch(e){}
	}
}

module.exports = rockBase;